<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="智能体ID" prop="agentId">
        <el-input
          v-model="queryParams.agentId"
          placeholder="请输入智能体ID"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="是否禁用" prop="isActive">
        <el-select
          v-model="queryParams.isActive"
          placeholder="请选择状态"
          clearable
          style="width: 200px"
        >
          <el-option label="正常" :value="0" />
          <el-option label="禁用" :value="1" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['admin:menu:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="roleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="智能体模式ID" prop="id" width="120" />
      <el-table-column
        label="智能体ID"
        prop="agentId"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="百炼的应用id"
        prop="appId"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="阿里智能媒体智能体ID"
        prop="aliAgentId"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="阿里智能媒体工作流ID"
        prop="aliWorkflowId"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="编码模式" align="center" prop="modeCode">
        <template #default="scope">
          <span>
            {{
              scope.row.modeCode === 0
                ? "语音通话"
                : scope.row.modeCode === 1
                ? "数字人通话"
                : scope.row.modeCode === 2
                ? "视觉通话"
                : scope.row.modeCode === 3
                ? "消息对话"
                : scope.row.modeCode === 4
                ? "视频通话"
                : scope.row.modeCode === 5
                ? "手机号通话"
                : "未知"
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="智能体图片" prop="agentModeUrl" width="300" />
      <el-table-column label="单独购买价格" prop="price" width="100" />
      <el-table-column label="单次使用消耗积分" prop="scoreCost" width="100" />

      <el-table-column label="购买方式" prop="isIncluded" width="100">
        <template #default="scope">
          <span>
            {{
              scope.row.isIncluded === 0
                ? "积分抵扣"
                : scope.row.isIncluded === 1
                ? "微信购买"
                : "未知"
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="AIGC按钮是否开启" prop="isAigcButton" width="100">
        <template #default="scope">
          <span>
            {{
              scope.row.isIncluded === 0
                ? "是"
                : scope.row.isIncluded === 1
                ? "否"
                : "未知"
            }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="显示顺序" prop="sort" width="100" />
      <el-table-column
        label="是否禁用"
        align="center"
        width="100"
        v-hasPermi="['admin:role:active']"
      >
        <template #default="scope">
          <el-switch
            v-model="scope.row.isActive"
            :active-value="0"
            :inactive-value="1"
            @change="(val) => handleStatusChange(scope.row, val)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip
            content="修改"
            placement="top"
            v-if="scope.row.isAdmin !== 1"
          >
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['admin:role:update']"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            content="删除"
            placement="top"
            v-if="scope.row.isAdmin !== 1"
          >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['admin:user:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="智能体id" prop="agentId">
              <el-select
                v-model="form.agentId"
                placeholder="请选择智能体"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in agentOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="阿里智能体id" prop="aliAgentId">
              <el-input
                v-model="form.aliAgentId"
                placeholder="请输入阿里智能体id"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="阿里工作流id" prop="aliWorkflowId">
              <el-input
                v-model="form.aliWorkflowId"
                placeholder="请输入阿里工作流id"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买方式" prop="isIncluded">
              <el-select v-model="form.isIncluded" placeholder="购买方式">
                <el-option label="积分抵扣" :value="0"></el-option>
                <el-option label="微信购买" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="模式" prop="modeCode">
              <el-select v-model="form.modeCode" placeholder="请选择模式">
                <el-option label="消息对话" :value="0"></el-option>
                <el-option label="语言对话" :value="1"></el-option>
                <el-option label="视觉对话" :value="2"></el-option>
                <el-option label="数字人通话" :value="3"></el-option>
                <el-option label="视频通话" :value="4"></el-option>
                <el-option label="手机号通话" :value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消耗积分" prop="scoreCost">
              <el-input
                v-model="form.scoreCost"
                placeholder="请输入积分"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import {
  listRole,
  agentmodemodeadd,
  agentmodemodeUpdate,
  agentModeInfo,
  activeID,
  listagent,deleteRemove
} from "@/api/min-app/agentmode";
const { proxy } = getCurrentInstance();
import { ElMessage, ElMessageBox } from "element-plus";

const roleList = ref([]);
const loading = ref(true);
const total = ref(0);
const dateRange = ref([]);
const open = ref(false);
const title = ref("");
const showSearch = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    page: 1,
    size: 10,
    agentId: "",
    isActive: undefined,
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询角色列表 */
function getList() {
  loading.value = true;

  const params = {
    page: queryParams.value.page,
    size: queryParams.value.size,
    agentId: queryParams.value.agentId || '-1',
    isActive: queryParams.value.isActive || -1, // 默认-1 表示全部
  };

  listRole(params).then((res) => {
    roleList.value = res.data.records || [];
    total.value = Number(res.data.total || 0);
    loading.value = false;
  });
}

/** 重置表单 */
function reset() {
  form.value = {
    agentId: "",
    aliAgentId: "",
    aliWorkflowId: "",
    isIncluded: 0,
    modeCode: "",
    scoreCost: "",
  };
  proxy.resetForm("menuRef");
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.roleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  agentModeInfo(-1).then((response) => {
    open.value = true;
    title.value = "添加用户";
    loadAgentOptions();
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  agentModeInfo(row.id).then((response) => {
    const { allDept, allRole, belongToDept, belongToRole, ...userInfo } =
      response.data;
    Object.assign(form.value, userInfo);
    open.value = true;
    title.value = "修改用户";
    loadAgentOptions();
    form.value.password = undefined;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["menuRef"].validate((valid) => {
    if (valid) {
      const payload = {
        ...form.value,
        agentId: form.value.agentId || "0",
        aliAgentId: form.value.aliAgentId || "",
        aliWorkflowId: form.value.aliWorkflowId || "",
        isIncluded: Number(form.value.isIncluded) || 0,
        modeCode: Array.isArray(form.value.modeCode)
          ? form.value.modeCode[0]
          : Number(form.value.modeCode) || 0,
        scoreCost: Number(form.value.scoreCost) || 0,
      };
      if (form.value.id) {
        agentmodemodeUpdate(payload).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        agentmodemodeadd(payload).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

//是否禁用
function handleStatusChange(row) {
  const text = row.isActive === 0 ? "启用" : "禁用";

  proxy.$modal
    .confirm(`确认要${text} "${row.agentId}" 用户吗?`)
    .then(() => activeID(row.id, row.isActive))
    .then(() => {
      proxy.$modal.msgSuccess(`${text}成功`);
    })
    .catch(() => {
      // 接口失败时回滚
      row.isActive = row.isActive === 0 ? 1 : 0;
    });
}

/** 搜索按钮 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

/** 重置按钮 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.page = 1;
  getList();
}

const agentOptions = ref([]);

/** 查询可选择的智能体列表（用于下拉） */
function loadAgentOptions() {
  const params = {
    page: 1,
    size: 9999,
  };

  listagent(params).then((res) => {
    agentOptions.value = res.data.records || [];
  });
}

// 删除
function handleDelete(row) {
  ElMessageBox.confirm("确认删除该智能体配置吗？", "提示", { type: "warning" })
    .then(async () => {
      const res = await deleteRemove(row.id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    })
    .catch(() => {});
}

getList();
</script>
